package com.aruba.rtmppushapplication.push;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.aruba.rtmppushapplication.push.natives.NativePush;
import com.aruba.rtmppushapplication.push.params.AudioParams;

/**
 * 对应音频推流的native层
 * Created by aruba on 2021/1/12.
 */
public class AudioPush implements IPush {
    private final static String tag = AudioPush.class.getSimpleName();
    private AudioParams audioParams;
    //录音
    private AudioRecord audioRecord;
    private int bufferSize;
    private RecordThread recordThread;
    private NativePush nativePush;

    public AudioPush(AudioParams audioParams) {
        this.audioParams = audioParams;
    }

    @Override
    public void init() {
        if (audioParams == null) {
            throw new NullPointerException("audioParams is null");
        }

        int channel = audioParams.getChannel() == 1 ?
                AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO;
        //最小缓冲区大小
        bufferSize = AudioRecord.getMinBufferSize(audioParams.getSampleRate(),
                channel, AudioFormat.ENCODING_PCM_16BIT);
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,//麦克风
                audioParams.getSampleRate(),
                channel,
                AudioFormat.ENCODING_PCM_16BIT,
                bufferSize
        );
    }

    @Override
    public int startPush() {
        if (recordThread != null && recordThread.isPushing) {
            return -1;
        }
        stopRecord();
        recordThread = new RecordThread();
        recordThread.start();

        return 0;
    }

    @Override
    public void stopPush() {
        stopRecord();
    }

    private synchronized void stopRecord() {
        if (recordThread != null) {
            recordThread.isPushing = false;
        }
    }

    public void setAudioParams(AudioParams audioParams) {
        this.audioParams = audioParams;
    }

    public AudioParams getAudioParams() {
        return audioParams;
    }

    public void setNativePush(NativePush nativePush) {
        this.nativePush = nativePush;
    }

    class RecordThread extends Thread {
        private boolean isPushing = true;

        @Override
        public void run() {
            audioRecord.startRecording();

            nativePush.setAudioParams(audioParams.getSampleRate(), audioRecord.getChannelCount());
            while (isPushing) {
                //采样数 *  2字节（16bit：一个采样占的比特数）
                byte[] buffer = new byte[nativePush.getInputSamples() * 2];
                int len = audioRecord.read(buffer, 0, buffer.length);
                if (len > 0) {
                    //交由native层处理
//                    Log.i(tag, "获取到了音频数据");
                    nativePush.pushAudio(buffer, len);
                }
            }

            audioRecord.stop();
        }
    }
}
